<?php

namespace App\Service\User\v1_2_1;

use App\Cache\UserRemarkCache;
use App\Helpers\AliyunUtil;
use App\Helpers\RedisUtil;
use App\Model\GiftLog;
use App\Model\Service\CacheService;
use App\Model\User;
use App\Model\UserProfile;
use App\Service\ServiceTrait\UserListTrait;
use App\Service\User\UserBaseService;
use Hyperf\DbConnection\Db;

/**
 * 主播列表
 */
class HostListService extends UserBaseService
{
    use UserListTrait;

    protected $pageNum = 30;

    public function handle()
    {
        $type = $this->request->input('type', 'rec');
        $page = $this->request->input('page', 1);
        $this->userId = $this->getUserId();
        $appId = $this->request->input('appid', 1);
        $channel = $this->request->input('channel',0);
//        $version = $this->request->input('version','1.0.0');
        //获取列表用户ID数组

//        if ($channel == 1002){
//            $userIds = $this->getTestUserIdV2();
//        }else{
            $userIds = $this->getUserIds($type, $appId);
//        }

        //筛选后的处理结果
        $this->doSelect($userIds);

        $ret = ['list' => []];
        if (empty($userIds)) return $ret;
        $start = ($page - 1) * $this->pageNum;
        $userIds = array_slice($userIds, $start, $this->pageNum);
//        shuffle($userIds);
        $usersInfo = UserProfile::getUsersProfile($userIds, true, true);
        $selfProfile = UserProfile::getProfile($this->userId);
        //已经搭讪过的
        $superChatUserIds = []; //GiftLog::checkSendUserIds($this->userId, GiftLog::FROM_SUPER_CHAT, 7200);
        //IM账号
        $imAccounts = User::getImAccounts($userIds);
        array_walk($usersInfo, function ($userProfile) use (&$ret, $appId, $superChatUserIds, $type, $selfProfile, $imAccounts) {
            $item = $this->buildHostItem($userProfile, $selfProfile, $imAccounts);
            //1-聊天，2-撩Ta
            $item['chat_type'] = $this->checkChatBefore($userProfile['user_id']) ? 1 : 2;
            $item['remark'] = $this->userId != $userProfile['user_id'] ? (new UserRemarkCache())->getRemark($this->userId, $userProfile['user_id']) : '';
            $item['distance'] = $item['city'] = '';
            //照片墙
            $item['moment_pics'] = [];
            if ($userProfile['poster']) {
                $posters = explode(',', trim($userProfile['poster'], ','));
                foreach ($posters as $poster) {
                    $item['moment_pics'][] = AliyunUtil::imageResize(AliyunUtil::IMG_HOST . $poster, 250, 250);
                }
            }
            $ret['list'][] = $item;
        });
        //列表照片
        $this->packPhotos($ret['list'], $userIds);
        //标签
        $this->packNewTags($ret['list'], $userIds, 'host');
//        array_multisort(array_column($ret['list'], 'distance_value'), SORT_ASC, $ret['list']);
        return $ret;
    }

    /**
     * 获取用户列表（不同类型）
     */
    function getUserIds($type = 'rec', $appId = 1)
    {
        $userIds = [];
        switch ($type) {
                //精选
            case 'rec':
            case 'hot':
            case 'video':
            /**
             * 推荐分数排序
             */
//                $data = $this->getRecommendScoreUserId();
//
//                $noAvatarVrfyUserIds = UserProfile::getNoAvatarVrfy();
//
//                $userIds = array_diff($data,$noAvatarVrfyUserIds);
//
//                // 排除非正常女用户
//                $abnormalUser = UserProfile::getAbnormalUser();
//                $userIds = array_diff($userIds, $abnormalUser);
            /**
             * end
             */

                            $onlineIds = UserProfile::getOnlineRecHosts(1);
                $uids1 = CacheService::getHostsByCate(UserProfile::HOST_CATE_A);
                $uids2 = CacheService::getHostsByCate(UserProfile::HOST_CATE_B);
                $uids = array_merge($uids1, $uids2);

                $freeUids = UserProfile::getFreezeStatusUsers();

                $onlineIds = array_intersect($uids,$onlineIds);
                $userIds = array_merge($onlineIds, array_diff($uids, $onlineIds,$freeUids));
                break;
                //最新
            default:
                $userIds = UserProfile::getNewUsers(UserProfile::ROLE_HOST, 0, 1000);
                break;
        }
        return $userIds;
    }

    /**
     * 条件筛选
     * v1.2.2版本
     */
    function doSelect(&$userIds = [])
    {
        $where = $this->buildSelectWhere();
        if (!$where) return;
        return $userIds = UserProfile::where($where)->whereIn('user_id', $userIds)->pluck('user_id')->toArray();
    }

    function checkChatBefore($chatUserId = 0)
    {
        return RedisUtil::get("chat_start_{$this->userId}_{$chatUserId}");
    }

    function getTestUserId(){
        $where = [
            ['status', '=', User::STATUS_OK],
            ['avatar', '<>', 'default/fe_avatar.jpeg'],
            ['gender', 0],
            ['user_id', '<>', env('KEFU_UID2', 11)],
            ['user_id', '<>', env('KEFU_UID',7)],
            ['user_profile.role', '=', UserProfile::ROLE_HOST],
            ['user.phone','like','240%']
        ];
        $res = Db::table('user_profile')
            ->join('user','user.id', '=', 'user_profile.user_id')
            ->where($where)
            ->pluck('user_id')
            ->toArray();

        return $res;
    }

    function getTestUserIdV2(){
        $where = [
            ['status', '=', User::STATUS_OK],
            ['avatar', '<>', 'default/fe_avatar.jpeg'],
            ['gender', 0],
            ['user_id', '<>', env('KEFU_UID2', 11)],
            ['user_id', '<>', env('KEFU_UID',7)],
            ['user_profile.role', '=', UserProfile::ROLE_HOST],
            ['user_profile.updated_at', '<', date('Y-m-d H:i:s', strtotime('-30 day'))]
        ];
        $res = Db::table('user_profile')
            ->join('user','user.id', '=', 'user_profile.user_id')
            ->where($where)
            ->limit(40)
            ->pluck('user_id')
            ->toArray();

        return $res;
    }
}
